self.onmessage = (event: MessageEvent) => {
  const data = JSON.parse(event.data)
  const { objects, time, type, threshold } = data

  if (type === '时间') {
    let lists = objects.slice(0).filter((item: any) => Number(item.lat) > 0 || Number(item.lon) > 0)
    const timestamps = lists.map((item: any) => (item ? new Date(item.timestr).getTime() : null))

    if (time > 0) {
      const timeThreshold = time * 1000
      let i = 0
      while (i < lists.length) {
        if (lists[i] === undefined || timestamps[i] === null) {
          i++
          continue
        }
        const lastDate = timestamps[i]
        let x = i + 1
        while (
          x < lists.length &&
          (lists[x] === undefined || (timestamps[x] - lastDate < timeThreshold && timestamps[x] !== null))
        ) {
          lists[x] = undefined
          x++
        }
        i = x
      }
    }
    lists = lists.filter((item: any) => item !== undefined)
    self.postMessage(lists)
  } else {
    const filteredObjects: any[] = []
    for (let i = 0; i < objects.length; i++) {
      const currentObject = objects[i]
      let isDistanceValid = false
      let nextComparisonIndex = i + 1

      while (nextComparisonIndex < objects.length) {
        const targetObject = objects[nextComparisonIndex]
        const currDistance = distanceByLngLat(currentObject.lat, currentObject.lon, targetObject.lat, targetObject.lon)

        if (currDistance >= threshold) {
          isDistanceValid = true
          break
        }

        nextComparisonIndex++
      }

      if (isDistanceValid) {
        filteredObjects.push(currentObject)
        i = nextComparisonIndex - 1
      }
    }

    self.postMessage(filteredObjects)
  }
}

function distanceByLngLat(lat1, lon1, lat2, lon2) {
  const radLat1 = red(lat1)
  const radLat2 = red(lat2)
  const a = radLat1 - radLat2
  const b = red(lon1) - red(lon2)
  let s =
    2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)))
  s = s * 6378137.0 // 取WGS84标准参考椭球中的地球长半径(单位:m)
  s = Math.round(s * 10000) / 10000
  return s
}
function red(b) {
  return (b * Math.PI) / 180.0
}
